/*
 * Copyright Hundsun Technologies Inc. All Rights Reserved.
 */

package commonstorage

import (
	"github.com/golang/protobuf/proto"
	"hundsun.com/hsl/hschain/common/types"
	"hundsun.com/hsl/hschain/protos"
	pbcom "hundsun.com/hsl/hschain/protos/common"
	"hundsun.com/hsl/hschain/store/db"
)

// Service 公共的db操作对象
type Service struct {
	db db.Database
}

// NewCommonStore new common store
func NewCommonStore(d db.Database) (*Service, error) {
	if d == nil {
		return nil, types.ErrNilDbInstance
	}
	return &Service{db: d}, nil
}

// Get get key
func (s *Service) Get(key string, result protos.EnhancedProtoMessage) error {
	v, err := s.db.Get(GenStoreKey(key))
	if err != nil {
		return err
	}

	return proto.Unmarshal(v, result)
}

// Put put proto data
func (s *Service) Put(pd protos.EnhancedProtoMessage) error {
	kv, err := Kv(pd)
	if err != nil {
		return err
	}

	return s.db.Set(kv.Key, kv.Value)
}

// Kv proto data to KeyValue
func Kv(pd protos.EnhancedProtoMessage) (*pbcom.KeyValue, error) {
	kv := &pbcom.KeyValue{}
	kv.Key = GenStoreKey(pd.GetXXXKey())
	v, err := proto.Marshal(pd)
	if err != nil {
		return nil, err
	}
	kv.Value = v
	return kv, nil
}

// GenStoreKey generate store key
func GenStoreKey(key string) []byte {
	return []byte(db.DefaultNamespace + key)
}
